package uk.ac.lkl.common.ui;



import javax.swing.JTextField;

import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;


public class NumericTextField extends JTextField {

    private DocumentFilter filter = new DocumentFilter() {

        public void insertString(DocumentFilter.FilterBypass fb,
                                 int offset,
                                 String string,
                                 AttributeSet attr) throws BadLocationException {

            if (!isAllDigits(string))
                return;

            if (offset == 0 && string.charAt(0) == '0')
                return;

            fb.insertString(offset, string, attr);
        }


        public void replace(DocumentFilter.FilterBypass fb,
                            int offset,
                            int length,
                            String string,
                            AttributeSet attr) throws BadLocationException {
            if (!isAllDigits(string))
                return;

            if (offset == 0 && string.charAt(0) == '0')
                return;

            fb.replace(offset, length, string, attr);
        }


        private boolean isAllDigits(String string) {
            for (int i = 0; i < string.length(); i++) {
                char ch = string.charAt(i);
                if (!Character.isDigit(ch))
                    return false;
            }
            return true;
        }
    };


    public NumericTextField() {
        super();
        AbstractDocument document = (AbstractDocument) getDocument();
        document.setDocumentFilter(filter);
    }

}
